package com.piece.module.spider.executor.shape;

import com.piece.core.framework.support.convert.Convert;
import com.piece.module.spider.context.SpiderContext;
import com.piece.module.spider.executor.Spider;
import com.piece.module.spider.model.SpiderFlow;
import com.piece.module.spider.service.SpiderFlowService;
import com.piece.module.spider.support.SpiderNode;
import com.piece.module.spider.util.SpiderFlowUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Map;

/**
 * 子流程执行器
 */
@Slf4j
@Component
public class ProcessExecutor implements ShapeExecutor {

	public static final String FLOW_ID = "flowId";

	@Autowired
	private Spider spider;

	@Lazy
	@Resource
	private SpiderFlowService spiderFlowService;

	@Override
	public void execute(SpiderNode node, SpiderContext context, Map<String,Object> variables) {
		String flowId = node.getStringJsonValue(FLOW_ID);
		SpiderFlow spiderFlow = spiderFlowService.findById(Convert.toLong(flowId));
		if (null != spiderFlow) {
			log.info("执行子流程:{}", spiderFlow.getName());
			SpiderNode root = SpiderFlowUtil.loadXMLFromString(spiderFlow.getXml());
			spider.executeNode(null,root,context,variables);
		} else {
			log.info("执行子流程:{}失败，找不到该子流程", flowId);
		}
	}

	@Override
	public String supportShape() {
		return "process";
	}
}
